package com.garden.rocketmq.learn.demo.producer;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;

/**
 *  延时生产者 发送延时消息
 *  用于注重延时发送的场景，如订单状态检验消息
 * Created by Garden on 2020-08-11 21:24
 */
public class ScheduledMessageProducer {

    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {
        //实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("scheduled_message_producer_group");
        //设置NameServer的地址，Producer启动后通过NameServer获取目标Topic的路由信息
        producer.setNamesrvAddr("localhost:9876");
        //启动Producer实例
        producer.start();

        //发送消息
        for (int i = 0; i < 100; i++) {
            //创建消息，指定主题Topic，标签Tag，业务标识Key，消息体MsgBody [Tag可用于消息过滤，Key可用于消息查询]
            Message message = new Message("test_topic"
                    ,"scheduled_message_producer_tag"
                    ,"scheduled_message_producer_key." + i
                    ,("Scheduled Msg." + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            //设置消息延时等级 3 -> 10s
            message.setDelayTimeLevel(3);
            //发送
            producer.send(message);
        }
    }

}
